from coin.blockchain.blockchair.btc.native_private_client import \
    BtcNativePrivateClient as nprivc
from coin.blockchain.request_util import (
    retry_error, parse_currency_balance, parse_coin_key)
from coin.exchange.base.kr_rest.private_client_base import \
    ExWalletPrivateClientBase


class BtcPrivateClient(ExWalletPrivateClientBase):
  def __init__(self, *, blockchain_name, node_info=None, api_key=None):
    assert blockchain_name == 'bitcoin'
    node_info = node_info or 'https://api.blockchair.com'
    self._nprivc = nprivc(host=node_info, api_key=api_key)

  def query_account_balance_impl(self, *, address, currency, end_height=None):
    assert currency == 'BTC', currency
    balance = retry_error(
        self._nprivc.get_token_balance,
        address=address,
        end_height=end_height)
    balance = parse_currency_balance(currency, 'satoshi', balance)
    return balance

  def get_latest_block_number_timestamp(self):
    return retry_error(self._nprivc.get_latest_block_number_timestamp)

  def get_block_timestamp(self, block_number):
    return retry_error(self._nprivc.get_block_timestamp, block_number=block_number)


if __name__ == '__main__':
  key = parse_coin_key('../../coin_key/view/ledger01/hw_wallet/view_key.json')
  wallet_address = next(
    chain.access_key for chain in key.chain_keys if chain.blockchain == 'bitcoin')
  btc_client = BtcPrivateClient(
    api_key='C___GykNdtSiNPqvTy5YMuuclAmH23qI', blockchain_name='bitcoin')
  block_num, block_ts = btc_client.get_latest_block_number_timestamp()
  print(btc_client.query_account_balance_impl(
    address=wallet_address, 
    currency='BTC',
    end_height=block_num))
